//
//  DetailCompleteController.m
//  FruitsWholesaler
//
//  Created by sgone-2 on 16/4/19.
//  Copyright © 2016年 sgone. All rights reserved.
//

#import "DetailCompleteController.h"
#import "DetailCompleteCell.h"
#import "Common.h"
#import "DataSingleton.h"
#import "AFNetworking.h"
#import "MJRefresh.h"
#import "Toast+UIView.h"
#import "LoginViewController.h"
#import "MBProgressHUD.h"
#import "DDtailController.h"

@interface DetailCompleteController ()<UITableViewDelegate,UITableViewDataSource>
{

    NSMutableDictionary *list;
    UIView *view20w;
    UIButton *btnw;
    UIImageView *imageVieww;
    DetailCompleteCell *cell2;
    NSInteger  tag1;

}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
//网路请求
@property(nonatomic,strong) AFHTTPSessionManager *manager;
@property(nonatomic,strong)  DataSingleton *dataSingleton;

@end

@implementation DetailCompleteController



//afnetworking网络请求数据
- (AFHTTPSessionManager *)manager
{
    if (_manager == nil) {
        _manager  = [AFHTTPSessionManager manager];
    }
    return _manager;
}

-(void)dealloc
{

    [[NSNotificationCenter defaultCenter]removeObserver:self];

}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    //通知已发货页面刷新
//    [[NSNotificationCenter defaultCenter]postNotificationName:@"fahuo" object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(creatDate) name:@"fahuo" object:nil];
    
     self.tableView.backgroundColor = BACKGROUND1;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    list = [NSMutableDictionary dictionaryWithCapacity:0];
    self.dataSingleton  = [DataSingleton sharedDataSingleton];
    [self creatUI];
    [self creatDate];
    
    
}


-(void)creatUI
{
    view20w = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-64-46)];
    
    view20w.backgroundColor= BACKGROUND1;
    [self.view addSubview:view20w];
    
    imageVieww = [[UIImageView alloc]initWithFrame:CGRectMake((view20w.frame.size.width-80)/2, (view20w.frame.size.height-110-70)/2, 80, 110)];
    imageVieww.image = [UIImage imageNamed:@"null_default"];

    [view20w addSubview:imageVieww];
    
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(0,(view20w.frame.size.height-80-70)/2 + imageVieww.frame.size.height+10, view20w.frame.size.width, 40)];
    lbl.text = @"  还没有新的订单哦~";
    lbl.textColor = [UIColor grayColor];
    lbl.textAlignment  = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:18];
    [view20w addSubview:lbl];
    
    
    
    btnw  = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, ViewWidth, ViewHeight-64-46)];
    [btnw addTarget:self action:@selector(creatDate) forControlEvents:UIControlEventTouchUpInside];
    [view20w addSubview:btnw];
    view20w.hidden = YES;
    self.tableView.hidden = NO;
    //    btnw.backgroundColor = [UIColor greenColor];
    
    
}


-(void)creatDate
{
    
    //进行刷新控制
    [self sendAPI];
    
}



-(void)sendAPI

{
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    NSString *urlStr = [NSString stringWithFormat:@"%@order_summary_info",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataSingleton.phone , @"uToken" : self.dataSingleton.uToken , @"order_id" : self.order_id , @"status" : @"23"};
    
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if ([responseObject[@"error_flag"] intValue] == 0)
            
        {
            
            //            NSLog(@"dasdasdada %@",responseObject);
            if (![responseObject[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                [MBProgressHUD hideHUDForView:self.tableView animated:YES];
                [self.view makeToast:@"请检查网络"];
                return ;
            }
            else
            {
                NSDictionary *dict = responseObject[@"data"][@"info"];
                
                NSArray *array = dict[@"order_list"];
                if (array.count != 0 )
                {
                    list = [NSMutableDictionary dictionaryWithDictionary:dict];
                    view20w.hidden = YES;
                    self.tableView.hidden = NO;
                }
                else
                {
                    view20w.hidden = NO;
                    self.tableView.hidden = YES;
                }
            }
            
            
            [self.tableView reloadData];
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
            
            if ([responseObject[@"result_code"] isEqualToString:@"ERR-WHO-0005"]) {
                
                //将所有存储的数据进行清除，并且跳转到登录界面
                [self.dataSingleton removeLocalData:@"wTel"];
                LoginViewController *login = [[LoginViewController alloc]initWithNibName:nil bundle:nil];
                [self presentViewController:login animated:YES completion:nil];
                
            }
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        view20w.hidden = NO;
        self.tableView.hidden = YES;
        [self.view makeToast:@"请检查网络"];
        
    }];
    
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return    1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return [[list objectForKey:@"order_list"] count];
    //    return 20;
    
    
}



-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    
    
    if ([[list objectForKey:@"order_list"] count] != 0) {
        
        return 30 * 4/FDLaOt + 16 /FDLaOt;
    }
    
    else
    {
        return 0.1;
        
    }
    
    
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    
    if ([[list objectForKey:@"order_list"] count] != 0)
    {
        return  [self contentView];
    }
    else
    {
        return nil;
        
    }
  
}
-(UIView *)contentView
{
    UIView *view2 = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 0, 10)];
    view2.backgroundColor = BACKGROUND1;
    UIView *view3 = [[UIView alloc]initWithFrame:CGRectMake(0, 8/FDLaOt, ViewWidth, 30 * 4/FDLaOt )];
    view3.backgroundColor = [UIColor whiteColor];
    [view2 addSubview:view3];
    
    
    
    
    

    for (int i = 0; i < 3; i++) {
        
        UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, i * 30/FDLaOt, ViewWidth, 30/FDLaOt)];
        [view3 addSubview:lbl];
        lbl.textColor = [UIColor grayColor];
        lbl.font = [UIFont systemFontOfSize:13/FDLaOt];
        
        
        
        switch (i) {
            case 0:
                //                lbl.frame = CGRectMake(10,0, ViewWidth, 30/FDLaOt);
                lbl.font = [UIFont boldSystemFontOfSize:13/FDLaOt];
                lbl.textColor = [UIColor blackColor];
                lbl.text = [NSString stringWithFormat:@"所属代理商 :  %@",[list objectForKey:@"dealer_name"]];
                break;
            case 1:
                lbl.text = [NSString stringWithFormat:@"订单编号:   %@",[list objectForKey:@"order_id"]];
                break;
            case 2:
                lbl.frame = CGRectMake(10, 2* 30/FDLaOt - 3/FDLaOt, ViewWidth, 30/FDLaOt);
                lbl.text = [NSString stringWithFormat:@"    订单数:   %ld",[[list objectForKey:@"order_list"] count]];
                break;
            default:
                break;
        }
        
    }
    
    
    
    UIButton *btnPhone = [[UIButton alloc]initWithFrame:CGRectMake(ViewWidth - 100, 4 /FDLaOt, 80, 30/FDLaOt)];
    btnPhone.layer.masksToBounds = YES;
    btnPhone.layer.cornerRadius = 4.0;
    btnPhone.layer.borderWidth = 1.0f;
    btnPhone.layer.borderColor = BenSe_COLOR.CGColor;
    [view3 addSubview:btnPhone];
    [btnPhone setTitle:@"拨打电话" forState:UIControlStateNormal];
    btnPhone.titleLabel.font = [UIFont systemFontOfSize:13/FDLaOt];
    [btnPhone setTitleColor:BenSe_COLOR forState:UIControlStateNormal];
    btnPhone.tag = 1100;
    [btnPhone addTarget:self action:@selector(phone:) forControlEvents:UIControlEventTouchUpInside];
    
     NSLog(@"wdwadawda  %@",list);
    
    
    UILabel *lbl = [[UILabel alloc]initWithFrame:CGRectMake(10, 3 * 30/FDLaOt, ViewWidth, 12/FDLaOt)];
   lbl.text = [NSString stringWithFormat:@"送货距离:      近距离%@家",list[@"near_num"]];
    [view3 addSubview:lbl];
    lbl.textColor = [UIColor grayColor];
    lbl.font = [UIFont systemFontOfSize:13/FDLaOt];
    
   
    
    UILabel *lbl2 = [[UILabel alloc]initWithFrame:CGRectMake(10, 3 * 30/FDLaOt + 13/FDLaOt, ViewWidth, 12/FDLaOt)];
     lbl2.text = [NSString stringWithFormat:@"                      远距离%@家",list[@"far_num"]];
    [view3 addSubview:lbl2];
    lbl2.textColor = [UIColor grayColor];
    lbl2.font = [UIFont systemFontOfSize:13/FDLaOt];
    
    
    return view2;
    
}




#pragma 商家电话
-(void)phone:(UIButton *)sender
{
    
    UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"是否拨打商家电话?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alter show];
    alter.tag = 111;
    tag1 = sender.tag;
  
}


- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag==111)
    {
        
        
        
        NSString *button=[alertView buttonTitleAtIndex:buttonIndex];
        if ([button isEqualToString:@"确定"]) {
            
            if (tag1  == 1100) {
                
                //拨打电话
                NSString *phoneNumber = [@"tel://" stringByAppendingString:[NSString stringWithFormat:@"%@",[list objectForKey:@"dTel"]]];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
                
            }
            
            else
                
            {
                //拨打电话[list[tag] objectForKey:@"sTel"]
                NSString *phoneNumber = [@"tel://" stringByAppendingString:[NSString stringWithFormat:@"%@",[list[@"order_list"][tag1] objectForKey:@"sTel"]]];
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:phoneNumber]];
                
            }
            
            
        }
        else if([button isEqualToString:@"取消"])
        {
            
        }
    }
    
}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    return 30/FDLaOt *5 + 40/FDLaOt + 16/FDLaOt;
    
    
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    cell2 = [DetailCompleteCell cellWithTableView:tableView];
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    if ([list[@"order_list"] count] != 0)
    {
        
        NSDictionary *dict = list[@"order_list"][indexPath.row];
        cell2.dealer_name = list[@"dealer_name"];
        cell2.row = [NSString stringWithFormat:@"%d",indexPath.row];
        [cell2 loadCell:dict];
        
        cell2.btn2.tag = indexPath.row;
//        cell2.btn1.tag = indexPath.row;
        
        
        
        
//        [cell2.btn1 addTarget:self action:@selector(sure:) forControlEvents:UIControlEventTouchUpInside];
        [cell2.btn2 addTarget:self action:@selector(phone:) forControlEvents:UIControlEventTouchUpInside];
        
        NSString *status = [NSString stringWithFormat:@"%@", list[@"order_list"][indexPath.row][@"status"]];
        
        //
        //        NSLog(@"yyyyyyyy %@",status);
        int s = [status intValue];
        switch (s) {
            case 7:
                cell2.btn1.userInteractionEnabled = YES;
                  [cell2.btn1 setTitle:@"确认发货" forState:UIControlStateNormal];
                
                break;
                
            case 2:
                
                cell2.btn1.userInteractionEnabled = NO;
                [cell2.btn1 setTitle:@"已发货" forState:UIControlStateNormal];
                break;
                
            case 3:
                
                cell2.btn1.userInteractionEnabled = NO;
                [cell2.btn1 setTitle:@"已完成" forState:UIControlStateNormal];
                break;
                
            default:
                break;
        }
        
    }
    
    return cell2;
 
    
}



-(void)sure:(UIButton *)sender
{
    [MBProgressHUD showHUDAddedTo:self.tableView animated:YES];
    NSInteger row = sender.tag;
    NSString *oId = [NSString stringWithFormat:@"%@",list[@"order_list"][row][@"order_id"]];
    NSString *urlStr = [NSString stringWithFormat:@"%@order_send",SERVER_ADDRESS2];
    NSDictionary *params = @{@"wTel" : self.dataSingleton.phone , @"uToken" : self.dataSingleton.uToken , @"order_id" : oId };
    [self.manager POST:urlStr parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if ([responseObject[@"error_flag"] intValue] == 0)
        {
            
            
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            [self.view makeToast:@"发货成功!"];
            //刷新当前页面，前一页面进行通知刷新
            [self sendAPI];
            [[NSNotificationCenter defaultCenter]postNotificationName:@"fahuo" object:nil];
        }
        else
        {
            [MBProgressHUD hideHUDForView:self.tableView animated:YES];
            NSString *str = [NSString stringWithFormat:@"%@",responseObject[@"result_msg"]];
            [self.view makeToast:str];
            
            
            //            UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:str delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            //            [alter show];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [MBProgressHUD hideHUDForView:self.tableView animated:YES];
        [self.view makeToast:@"发货失败,请检查网络!"];
    }];
    
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

{
    NSDictionary *dict = list[@"order_list"][indexPath.row];
    DDtailController *dd = [[DDtailController alloc]initWithNibName:nil bundle:nil];
    dd.order_id = [NSString stringWithFormat:@"%@",dict[@"order_id"]];
    dd.dict = dict;
    dd.dealer_name = list[@"dealer_name"];
    
 
    if ([dd.order_id intValue] == 0) {
        
        
        return;
    }
    
    else
    {
    
        [self.navigationController pushViewController:dd animated:YES];
    
    }

}


@end
